<template>
  <!-- if you don't like line break ,then use <span> instead of the <div> -->
  <div>
    <h2>Carts</h2>
    <ul>
      <li v-for="(v, i) of fruits" :key="i">
        <span> name(icon):{{ v.name }} </span>
        <span> price:{{ v.price }} </span>
        <span>
          counter:<Counter
            :quantity="v.quantity"
            :index="i"
            @add="add"
            @sub="sub"
          ></Counter>
        </span>
      </li>
    </ul>
  </div>
</template>
<script>
import Counter from "./Counter";

export default {
  components: { Counter },
  data() {
    return {
      fruits: [
        { name: "🍎 ", price: 3.1, quantity: 3 },
        { name: "🍌 ", price: 2.1, quantity: 10 },
        { name: "🍐 ", price: 4.1, quantity: 0 },
      ],
    };
  },
  methods: {
    //   by the index of the item in the fruits list,do the add/sub operation on the corresponding item.
    add(index) {
      this.fruits[index].quantity++;
    },
    sub(index) {
      // the item reference to the object of the fruitList item object(like a pointer)
      let item = this.fruits[index];
      //   quantity is a independent variable
      let quantity = item.quantity;
      if (quantity > 0) {
        // this.fruits[index].quantity--;
        item.quantity--;
      }
    },
  },
};
</script>